<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="登记时间" prop="arrivalTime" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_record_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="applyTime" style="width: 308px">
              <el-date-picker
                v-model="createTimeRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:admCarStore:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:admCarStore:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:admCarStore:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:admCarStore:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="admCarStoreList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="登记时间" align="center" prop="registerTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.registerTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车牌号" align="center" prop="carNumber" />
        <el-table-column label="车辆性质" align="center" prop="type" >
          <template #default="scope">
            <dict-tag :options="car_type_options" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="车型" align="center" prop="model" >
          <template #default="scope">
            <el-tooltip :content="scope.row.model" placement="top" :disabled="!scope.row.model">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.model }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="借出状态" align="center" prop="isLend">
              <template #default="scope">
                <dict-tag :options="asset_lend_status" :value="scope.row.isLend" />
              </template>
            </el-table-column>
        <el-table-column label="排量" align="center" prop="displacement" />
        <el-table-column label="审批状态" align="center" prop="status" >
          <template #default="scope">
            <dict-tag :options="approval_record_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark">
          <template #default="scope">
            <el-tooltip :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.remark }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:admCarStore:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:admCarStore:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改车辆登记对话框 -->
    <el-dialog 
      :title="dialog.title" 
      v-model="dialog.visible" 
      width="900px" 
      append-to-body
      class="seal-dialog"
    >
      <template #default>
        <el-form ref="admCarStoreFormRef" :model="form" :rules="rules" label-width="140px" label-position="left" style="padding: 20px 0 20px 24px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="登记人" prop="registerId">    
                <el-input v-model="form.registerName" placeholder="请输入登记人" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="登记时间" prop="registerTime">
                <el-date-picker clearable
                  v-model="form.registerTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择登记时间"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="车牌号" prop="carNumber" style="display: flex; align-items: center; gap: 16px;">
                <!-- 车牌选择器 -->
                <CarPlateSelector :key="carPlateKey" v-model="form.carNumber" />
                <!-- 显示选中的车牌 -->
                <span style="min-width: 120px;margin-left: 20px;">选中: {{ form.carNumber }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="车型" prop="model">
                <el-input v-model="form.model" placeholder="请输入车型" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="排量" prop="displacement">
                <el-input v-model="form.displacement" placeholder="请输入排量" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="车辆性质" prop="type">
                <el-select
                  v-model="form.type"
                  placeholder="请选择车辆性质"
                  style="width: 100%;"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in car_type_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="借出状态" prop="isLend">
                <el-select
                  v-model="form.isLend"
                  placeholder="请选择借出状态"
                  style="width: 100%;"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="item in asset_lend_status"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="3"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AdmCarStore" lang="ts">
import { listAdmCarStore, getAdmCarStore, delAdmCarStore, addAdmCarStore, updateAdmCarStore } from '@/api/general/administration/car/store';
import { AdmCarStoreVO, AdmCarStoreQuery, AdmCarStoreForm } from '@/api/general/administration/car/store/types';
import { useUserStore } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const admCarStoreList = ref<AdmCarStoreVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 用户信息
const userStore = useUserStore();

// 用于强制刷新 CarPlateSelector
const carPlateKey = ref(0);

// 引入数据字典
const { car_type_options, approval_record_status, asset_lend_status } = toRefs<any>(proxy?.useDict('car_type_options', 'approval_record_status', 'asset_lend_status'));

const queryFormRef = ref<ElFormInstance>();
const admCarStoreFormRef = ref<ElFormInstance>();
// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);


const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const initFormData: AdmCarStoreForm = {
  id: undefined,
  registerId: userStore.userId,
  registerName: userStore.name,
  model: undefined,
  registerTime: formatLocalDate(),
  carNumber: undefined,
  type: undefined,
  displacement: undefined,
  isLend: undefined,
  remark: undefined,
  status: undefined,
}
const data = reactive<PageData<AdmCarStoreForm, AdmCarStoreQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    registerId: undefined,  
    model: undefined,
    registerTime: undefined,
    carNumber: undefined,
    type: undefined,
    displacement: undefined,
    isLend: undefined,
    remark: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    registerId: [
    { required: true, message: "登记人不能为空", trigger: "blur" }
    ],
    registerTime: [
      { required: true, message: "登记时间不能为空", trigger: "change" }
    ],
    carNumber: [
      { 
        required: true, 
        message: "车牌号不能为空", 
        trigger: "change" // 使用 change 而不是 blur，因为是选择器组件
      },
      { 
        pattern: /^[\u4e00-\u9fa5][A-Z][A-Z0-9]{5}$/, 
        message: "请输入正确的车牌号", 
        trigger: "change" 
      }
    ],
    model: [
      { required: true, message: "车型不能为空", trigger: "blur" }
    ],
    displacement: [
      { required: true, message: "排量不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "车辆性质不能为空", trigger: "change" }
    ],
    isLend: [
      { required: true, message: "借出状态不能为空", trigger: "change" }
    ],
    remark: [
      { required: false }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询车辆登记列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listAdmCarStore(params);
    admCarStoreList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  // 强制刷新子组件
  carPlateKey.value += 1;
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  admCarStoreFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
    queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdmCarStoreVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加车辆登记";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AdmCarStoreVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getAdmCarStore(_id);
  // 赋值到表单
  Object.assign(form.value, res.data);

  // --- 处理车牌号回显 ---
  carPlateKey.value += 1;
  form.value.carNumber = res.data.carNumber || '';
  dialog.visible = true;
  dialog.title = "修改车辆登记";

  console.log("回显表单数据:", form.value);
};

/** 提交按钮 */
const submitForm = () => {
  admCarStoreFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAdmCarStore(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addAdmCarStore(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: AdmCarStoreVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除车辆登记编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAdmCarStore(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/admCarStore/export', {
    ...queryParams.value
  }, `admCarStore_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
<style scoped>
.seal-dialog :deep(.el-dialog__header) {
  text-align: center;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto !important;
  display: block; /* 确保是块级元素 */
}
</style>
